package worker

import (
	"gitee.com/Cookie_XiaoD/crontab/common"
	"math/rand"
	"os/exec"
	"time"
	"log"
)

//任务执行器
type Executer struct {
}

var (
	G_Executer *Executer
)

func InitExecuter() (err error) {
	G_Executer = &Executer{}
	return
}

//ExecuteJob 执行任务
func (executer *Executer) ExecuteJob(info *common.JobExecuteInfo) {
	go func() {

		var (
			cmd       *exec.Cmd
			exeResult *common.JobExecuteResult
			jobLock   *JobLock
			err       error
		)

		exeResult = &common.JobExecuteResult{
			JobExecuteInfo: info,
			StartTime:      time.Now(),
			Output:         make([]byte, 0),
		}

		jobLock = G_JobMgr.CreateJobLock(info)

		//为了多个worker之间都有机会抢到锁，这里随机睡眠
		time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)

		err = jobLock.TryLock()
		defer jobLock.Unlock()
		if err != nil {
			log.Println("**************"+info.Job.Name+":抢锁失败")
			exeResult.Err = err
			exeResult.EndTime = time.Now()
		} else {
			log.Println("**************"+info.Job.Name+":抢锁成功")
			//linux下
			//exec.CommandContext(context.TODO(),"/bin/bash","-c",info.Job.Command)
			//windows 下
			cmd = exec.CommandContext(info.CancelCtx, "D:\\Development\\Cygwin\\bin\\bash.exe", "-c", info.Job.Command)

			//将任务执行结果通过channel通知调度器,调度器输出结果，并从executing中移除相应任务
			exeResult.EndTime = time.Now()
			exeResult.Output, exeResult.Err = cmd.Output()
		}

		G_scheduler.PushJobExeResult(exeResult)

	}()
}
